package com.mymoney.resources;

import java.util.List;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.mymoney.beans.StoreBean;
import com.mymoney.persistence.PersistenceContext;
import com.mymoney.persistence.managers.StoreManager;
import com.mymoney.utils.ServiceUtils;

@Path("/stores")
public class StoreResource extends AbstractWebResource {
	
	@GET
	@Produces({ MediaType.APPLICATION_JSON })
	public Response list() {
		Response response = null;
		PersistenceContext persistenceContext = PersistenceContext.getPersistenceContext();
		
		try
		{
			if(persistenceContext != null)
			{
				StoreManager storeManager = persistenceContext.getStoreManager();
				List<StoreBean> storeList = storeManager.list();
				response = Response.ok(storeList).type(MediaType.APPLICATION_JSON).build();
			}
			else
			{
				throw new NullPointerException();
			}
		}catch (Exception e) {
			response = ServiceUtils.getErrorResponse(111, e);
		}
		
		return response;
	}
	
	
	@POST
	@Path("/store")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response add(final StoreBean storeBean) {
		Response response = null;
		PersistenceContext persistenceContext = PersistenceContext.getPersistenceContext();
		try {
			
			if(persistenceContext != null)
			{
				StoreManager storeManager = persistenceContext.getStoreManager();
				storeManager.add(storeBean);
				response = Response.ok(storeBean).type(MediaType.APPLICATION_JSON).build();
			}
			else
			{
				throw new NullPointerException();
			}
		} catch (Exception e) {
			response = ServiceUtils.getErrorResponse(111, e);
		}
		return response;
	}
}
